package com.gao.frame.study.shop.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-09-24 15:36
 */
@SpringBootApplication
@EnableDiscoveryClient
public class OrderTestApplication {
    @RestController
    public class NacosController{

        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @Autowired
        private RestTemplate restTemplate;

        @Value("${spring.application.name}")
        private String appName;

        @GetMapping("/echo/app-name")
        public String echoAppName(){
            //使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问
            long l = System.currentTimeMillis();
            ServiceInstance serviceInstance = loadBalancerClient.choose("shop-user");
            String url = String.format("http://%s:%s/user/%s",serviceInstance.getHost(),serviceInstance.getPort(),1);
            System.out.println("request url:"+url);
            String forObject = restTemplate.getForObject(url, String.class);
            System.out.println(String.format("查询消耗时间：%s",System.currentTimeMillis()-l));
            return forObject;
        }

    }

    //实例化 RestTemplate 实例
    @Bean
    public RestTemplate restTemplate(){

        return new RestTemplate();
    }

    public static void main(String[] args) {

        SpringApplication.run(OrderTestApplication.class,args);
    }
}
